<?php
namespace app\home\controller;

use app\common\logic\Check;
use think\Request;
use think\Db;
use think\Session;
use think\Controller;
use app\user\controller\Verificationcode;
use app\common\logic\Sms;
/**
 * Login Controller
 */
class Login extends Controller
{

    public function index() {
        $this->assign('title', '共享充电宝设备');
        return $this->fetch('login');
    }

    /**
     * 登录
     */
	public function login(){
        Session::set('smscode', 'abcd');
	    if ( Request::instance()->isPost() ) {
	        // 做一个简单的登录 组合where数组条件
            $code = Request::instance()->post('code', '');
            $backFunc = Request::instance()->post('backFunc', '');
            $msg = '';
            if( empty( $code ) ) {
                exit_msg_callback($backFunc, '验证码错误');
            }
	        $phone = Request::instance()->post('phone', '', '');
	        if( empty( $phone ) || !Check::checkPhone($phone)) {
	            exit_msg_callback($backFunc, '手机号码错误');
	        }

            $oid = 1;
            $smsCode = cache('VerificationCode|oid='.$oid.'+number='.$phone);
            if (empty($smsCode)) {
                exit_msg_callback($backFunc, '请先获取验证码');
            } elseif ($smsCode != $code) {
                exit_msg_callback($backFunc, '验证码错误');
            }
            $role = Request::instance()->post('role', '');
            if( empty( $role ) ) {
                exit_msg_callback($backFunc, '身份错误！');
            }

            switch ($role) {
                case 1: // 代理商
                case 2: // 地推
                    $data = Db::name('agent')->where(['phone' => $phone,'is_use' => 1])->find();
                    if (empty($data)) {
                        exit_msg_callback($backFunc, '用户不存在！');
                    }
                    break;
                case 3: // 商户
                    $data = Db::name('seller')->where(['phone' => $phone,'status' => 1,'is_delete' => 1])->find();
                    if (empty($data)) {
                        exit_msg_callback($backFunc, '用户不存在！');
                    }
                    break;
                default:
                    exit_msg_callback($backFunc, '用户不存在！');
            }

            Session::set('phone', $data['phone']);
            Session::set('role', $role);
            Session::set('id', $data['id']);
            exit_msg_callback($backFunc, '登录成功！', 1);
	    }
	}

    /**
     * 退出
     */
    public function logout()
    {
       	session(null);
       	cookie(null);
        session_destroy();
        $this->redirect(\think\Request::instance()->root().'/home/Login/index');
    }

    /**
     * 获取短信验证码
     */
    public function smscode()
    {
        $verificationcode = new Sms();
        $phone = Request::instance()->param('phone');
        $result = $verificationcode->sendSms($phone);
        return json_encode($result);
    }
}

